﻿using DbBackupAssist.Extensions;
using IWshRuntimeLibrary;
using NLog;

namespace DbBackupAssist
{
    public partial class OptionsForm : Form
    {
        private ILogger _logger = LogManager.GetCurrentClassLogger();

        public OptionsForm()
        {
            InitializeComponent();
        }

        private void OptionsForm_Load(object sender, EventArgs e)
        {
            LoadConfiguration();
        }

        private void WfyShowFolderSelect_Click(object sender, EventArgs e)
        {
            if (this.WfyFolderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                WfyTextBoxBackupDirPath.Text = WfyFolderBrowserDialog.SelectedPath;
            }
        }

        private void WfyButtonOK_Click(object sender, EventArgs e)
        {
            try
            {
                this.SaveConfiguration();

                FolderExtension.ShareFolder(WfyTextBoxShareFolderName.Text, WfyTextBoxBackupDirPath.Text);

                DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
            }
        }

        private void WfyButtonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void WfyToolStripMenuItemDeleteItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem selectedItem in WfyListViewDatabases.SelectedItems)
            {
                WfyListViewDatabases.Items.Remove(selectedItem);
            }
        }

        private void WfyToolStripMenuItemAddItem_Click(object sender, EventArgs e)
        {
            var inputDialog = new InputDialog();
            inputDialog.TopMost = true;

            if (inputDialog.ShowDialog() == DialogResult.OK)
            {
                var newDatabaseItem = new ListViewItem();
                newDatabaseItem.ImageIndex = 3;
                newDatabaseItem.Text = inputDialog.InputText;

                WfyListViewDatabases.Items.Add(newDatabaseItem);
            }
        }

        private void LoadConfiguration()
        {
            try
            {
                var configuration = DbConfigurationManager.Load();

                if (configuration != null)
                {
                    WfyTextBoxRemoteSqlServer.Text = configuration.RemoteSqlServer?.SqlInstance;
                    WfyTextBoxRemoteUserName.Text = configuration.RemoteSqlServer?.UserName;
                    WfyTextBoxRemotePassword.Text = configuration.RemoteSqlServer?.Password;

                    WfyTextBoxLocalSqlServer.Text = configuration.LocalSqlServer?.SqlInstance;
                    WfyTextBoxLocalUserName.Text = configuration.LocalSqlServer?.UserName;
                    WfyTextBoxLocalPassword.Text = configuration.LocalSqlServer?.Password;

                    WfyListViewDatabases.Items.Clear();

                    foreach (var databaseName in configuration.DatabaseNames)
                    {
                        var newDatabaseItem = new ListViewItem();
                        newDatabaseItem.ImageIndex = 3;
                        newDatabaseItem.Text = databaseName;

                        WfyListViewDatabases.Items.Add(newDatabaseItem);
                    }

                    WfyDateTimePickerExecuteTime.Value = new DateTime(DateOnly.FromDateTime(DateTime.Today),
                                                                       TimeOnly.FromTimeSpan(configuration.BackupTime));

                    WfyNumericUpDownRetentionDays.Value = configuration.RetentionDays;
                    WfyTextBoxBackupDirPath.Text = configuration.BackupDirectory;
                    WfyTextBoxShareFolderName.Text = configuration.ShareFolderName;

                    WfyTextBoxLoginAccount.Text = configuration.LoginAccount;
                    WfyTextBoxLoginPassword.Text = configuration.LoginPassword;
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
            }
        }

        private void SaveConfiguration()
        {
            try
            {
                var configuration = new DbBackupConfiguration();

                configuration.RemoteSqlServer.SqlInstance = WfyTextBoxRemoteSqlServer.Text;
                configuration.RemoteSqlServer.UserName = WfyTextBoxRemoteUserName.Text;
                configuration.RemoteSqlServer.Password = WfyTextBoxRemotePassword.Text;

                configuration.LocalSqlServer.SqlInstance = WfyTextBoxLocalSqlServer.Text;
                configuration.LocalSqlServer.UserName = WfyTextBoxLocalUserName.Text;
                configuration.LocalSqlServer.Password = WfyTextBoxLocalPassword.Text;

                foreach (ListViewItem databaseItem in WfyListViewDatabases.Items)
                {
                    configuration.DatabaseNames.Add(databaseItem.Text);
                }

                configuration.BackupTime = TimeOnly.FromDateTime(WfyDateTimePickerExecuteTime.Value).ToTimeSpan();

                configuration.RetentionDays = Convert.ToInt32(WfyNumericUpDownRetentionDays.Value);
                configuration.BackupDirectory = WfyTextBoxBackupDirPath.Text;
                configuration.ShareFolderName = WfyTextBoxShareFolderName.Text;

                configuration.LoginAccount = WfyTextBoxLoginAccount.Text;
                configuration.LoginPassword = WfyTextBoxLoginPassword.Text;

                configuration.Save();
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
            }
        }

        private void WfyCheckBoxAutoStart_CheckedChanged(object sender, EventArgs e)
        {
            //快捷方式的描述、名称的默认值是当前的进程名，自启动默认为正常窗口，一般情况下不需要手动设置
            //设置快捷方式的描述，
            AutoStart.Instance.QuickDescribe = "数据库自动备份";
            //设置快捷方式的名称
            AutoStart.Instance.QuickName = "数据库自动备份";
            //设置自启动的窗口类型，后台服务类的软件可以设置为最小窗口
            AutoStart.Instance.WindowStyle = WshWindowStyle.WshMinimizedFocus;

            //快捷方式设置true时，有就忽略、没有就创建，自启动快捷方式只能存在一个
            //设置开机自启动，true 自启动，false 不自启动
            AutoStart.Instance.SetAutoStart(WfyCheckBoxAutoStart.Checked);
            //设置桌面快捷方式，true 创建桌面快捷方式（有就跳过，没有就创建），false 删除桌面快捷方式
            AutoStart.Instance.SetDesktopQuick(true, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icons\\database.ico"));
        }
    }
}
